package pl.edu.uj.tcs.blef.protocol;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.Client;
import pl.edu.uj.tcs.blef.server.Table;

public class KickRequestHandler extends AbstractTableHandler {

	public KickRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		KickRequest ctr = (KickRequest)request;
		if(!table.isOperator(socket)) {
			System.out.println("Unauthorized operator request from socket: " + socket.getInetAddress().getHostAddress());
			try {
				Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			} catch (Exception e){}
		} else {
			if(!table.getPlayers().contains(new Client(ctr.getPlayerNick(), socket, 1)) &&
					!table.getAwaitingPlayers().contains(new Client(ctr.getPlayerNick(), socket, 1))){
				try {
					Request r = new InvalidParametersErrorFactory().build(null, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				} catch (Exception e){}
			} else {
				Client client = null;
				for(Client c: table.getPlayers()){
					if(c.getNick().equals(ctr.getPlayerNick())) client = c;
				}
				
				for(Client c: table.getAwaitingPlayers()){
					if(c.getNick().equals(ctr.getPlayerNick())) client = c;
				}
			
				String[] param = new String[1]; param[0] = "OK Kicked "+ctr.getPlayerNick();
				try {
					Request r = new OKRequestFactory().build(param, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				} catch (Exception e){}
				
				try {
					table.checkTerminate();
					client.getSocket().close();
					table.getPlayers().remove(client);
					table.getAwaitingPlayers().remove(client);
				} catch (IOException e) {}
			}
		}
	}

}
